package com.ash.other;

import com.ash.util.ConnectionUtil;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Objects;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/6 21:15
 * @Author : Chen Chao
 * @File : connection.com.ash.other.Test05.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 图片存储与取出
 */
public class Test05 {
    public static void main(String[] args) {
        int id = 1;
        File file = new File("src/com/img/pig02.ico");
        File file2 = new File("src/com/img/gg02.ico");
        store(id,file);
        load(id, file2);
    }

    private static void load(int id, File file) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            connection = ConnectionUtil.getConnection();
            ps = Objects.requireNonNull(connection).
                    prepareStatement("select * from picture where id= ?");
            ps.setObject(1, id);
            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                /*获取图片*/
                Blob blob = resultSet.getBlob("blob");
                /*图片转流*/
                InputStream binaryStream = blob.getBinaryStream();
                /*流转文件*/
                Files.copy(binaryStream, Paths.get(file.getPath()));
            }
        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection, ps, resultSet);
        }
    }

    private static void store(int id, File file) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = ConnectionUtil.getConnection();
            ps = Objects.requireNonNull(connection).
                    prepareStatement("insert into picture values(?,?)");
            ps.setObject(1, id);
            ps.setBlob(2, new FileInputStream(file));
            ps.executeUpdate();
        } catch (SQLException | FileNotFoundException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection, ps, null);
        }
    }
}
